<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="UTF-8">
    <title>电子签名</title>
    <style>
        canvas {
            border: 1px solid black;
        }
        button {
            margin: 10px;
        }
    </style>
</head>
<body>
<canvas id="signatureCanvas" width="400" height="200"></canvas>
<br>
<button id="clearButton">清除签名</button>
<button id="saveButton">保存签名</button>

<script>
    const canvas = document.getElementById("signatureCanvas");
    const ctx = canvas.getContext("2d");

    let isDrawing = false;
    let lastX = 0;
    let lastY = 0;

    canvas.addEventListener("mousedown", startDrawing);
    canvas.addEventListener("mousemove", draw);
    canvas.addEventListener("mouseup", stopDrawing);
    canvas.addEventListener("mouseout", stopDrawing);

    function startDrawing(e) {
        isDrawing = true;
        [lastX, lastY] = [e.offsetX, e.offsetY];
    }

    function draw(e) {
        if (!isDrawing) return;
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        [lastX, lastY] = [e.offsetX, e.offsetY];
    }

    function stopDrawing() {
        isDrawing = false;
    }

    const clearButton = document.getElementById("clearButton");

    clearButton.addEventListener("click", clearCanvas);

    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    const saveButton = document.getElementById("saveButton");

    saveButton.addEventListener("click", saveCanvas);

    function saveCanvas() {
        const image = canvas.toDataURL("image/png");
        const link = document.createElement("a");
        link.download = "signature.png";
        link.href = image;
        link.click();
    }

</script>
</body>
</html>
